<?php

class WordToHtmlController
{
    public function index()
    {
        require 'vendor/autoload.php';

        $base64 = "upload";

        $config = array(
            "pathFormat" => '/public/uploads/word/{yyyy}{mm}{dd}/{time}{rand:6}',
            "maxSize" => 102400000,
            "allowFiles" => [".docx"]
        );
        $fieldName = 'upfile';

        include 'Uploader.class.php';
        $up = new Uploader($fieldName, $config, $base64);
        $path = ltrim($up->getFileInfo()['url'], '/');

              //        $phpWord = \PhpOffice\PhpWord\IOFactory::load('public/uploads/word/20211029/test.docx');
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($path);

        // 直接输出到页面显示
              //        $phpWord->save('php://output', 'HTML');

        $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');

        header("Content-Type:text/html; charset=utf-8");
        exit($this->replaceImageSrc($xmlWriter->getContent()));
          //        exit($xmlWriter->getContent());
    }

    /**
     * 将HTML代码中的所有图片地址替换
     * @param $content string 要查找的内容
     * @return string
     */
    private function replaceImageSrc($content)
    {
        $preg = '/(\s+src\s?\=)\s?[\'|"]([^\'|"]*)/is'; // 匹配img标签的正则表达式
        preg_match_all($preg, $content, $allImg); // 匹配所有的img

        if (!$allImg)
            return $content;

        foreach ($allImg[0] as $k => $v) {
            $old = ltrim($v, '" src=');

            preg_match('/^(data:\s*image\/(\w+);base64,)/', $old, $temp);
            $tempType = $temp[2];   // 获取类型

            // 判断目录是否存在，不存在时创建
            $tempFilePath = 'public/uploads/word_images/' . date('Y-m-d', time());
            if (!file_exists($tempFilePath))
                mkdir($tempFilePath);

            // 拼接完整路径
            $tempFileName = $tempFilePath . '/word_image_' . time() . $k . '.' . $tempType;
            $base64 = str_replace($temp[1], '', $old);

            file_put_contents($tempFileName, base64_decode($base64));

            // 替换路径字符串
            $content = str_replace($old, $tempFileName, $content);
        }
        return $content;
    }
}